import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions

from config.setting import browser_type, WAIT_TIME, headless
from utils.logging_tool.recordlog import logs


def init_driver():
    # 初始化浏览器对象
    browser_mapping = {
        'Chrome': webdriver.Chrome,
        'Edge': webdriver.Edge,
        'Firefox': webdriver.Firefox
    }
    # 根据浏览器类型创建Options对象，无头模式
    options = None
    if browser_type.capitalize() == 'Chrome':
        options = ChromeOptions()
        options.add_argument('--headless')
    elif browser_type.capitalize() == 'Edge':
        options = EdgeOptions()
        options.add_argument('--headless')
    elif browser_type.capitalize() == 'Firefox':
        options = FirefoxOptions()
        options.add_argument('--headless')

    if browser_type.capitalize() in browser_mapping:
        return browser_mapping.get(browser_type.capitalize())(options=options if headless else None)


# fixture 每次运行初始化一个浏览器驱动
@pytest.fixture()  # 每个用例都需要重新登录，若整个项目只需要登录一次使用：scope='session'
def get_driver():
    # 1.初始化浏览器
    global driver  # 定义全局变量driver
    driver = init_driver()
    driver.implicitly_wait(WAIT_TIME)
    driver.maximize_window()
    # 2.用例执行，返回driver
    yield driver
    # 3.用例后置，关闭浏览器
    driver.quit()


# 登录状态的前置应用
@pytest.fixture(autouse=True)  # 每条用例都需要重新登录，若整个项目只需要登录一次使用：scope='session'
def login_driver(get_driver):
    logs.info("前置条件登录-正在登录")
    driver = get_driver
    from data.login_pre.login_page import LoginPage
    login_page = LoginPage(driver)
    username, password = "admin", "admin"
    login_page.login(username, password)
    logs.info("登录成功")
    return driver
